<template>
  <div ref="nav" class="ui fixed inverted stackable pointing menu"
       :class="{'transparent':route.name==='home' && clientSize.clientWidth>768}">
    <div class="ui container">
      <router-link to="/">
        <h3 class="ui header item m-blue">{{ blogName }}</h3>
      </router-link>
      <router-link to="/home" class="item" :class="{'m-mobile-hide': mobileHide,'active':route.name==='home'}">
        <i class="home icon"></i>首页
      </router-link>
      <el-dropdown trigger="click" @command="categoryRoute">
				<span class="el-dropdown-link item" :class="{'m-mobile-hide': mobileHide,'active':route.name==='category'}">
					<i class="idea icon"></i>分类<i class="caret down icon"></i>
				</span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item :command="category.name" v-for="(category,index) in categoryList" :key="index">
              {{ category.name }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <router-link to="/archives" class="item" :class="{'m-mobile-hide': mobileHide,'active':route.name==='archives'}">
        <i class="clone icon"/>归档
      </router-link>
      <router-link to="/moments" class="item" :class="{'m-mobile-hide': mobileHide,'active':route.name==='moments'}">
        <i class="comment alternate outline icon"></i>动态
      </router-link>
      <router-link to="/friends" class="item" :class="{'m-mobile-hide': mobileHide,'active':route.name==='friends'}">
        <i class="users icon"></i>友人帐
      </router-link>
      <router-link to="/about" class="item" :class="{'m-mobile-hide': mobileHide,'active':route.name==='about'}">
        <i class="info icon"></i>关于我
      </router-link>
      <el-autocomplete v-model="queryString" :fetch-suggestions="debounceQuery" placeholder="Search..."
                       class="right item m-search" :class="{'m-mobile-hide': mobileHide}"
                       popper-class="m-search-item" @select="handleSelect">
        <template #suffix>
          <i class="search icon el-input__icon"></i>
        </template>
        <template #default="{ item }">
          <div class="title">{{ item.title }}</div>
          <span class="content">{{ item.content }}</span>
        </template>
      </el-autocomplete>
      <button class="ui menu black icon button m-right-top m-mobile-show" @click="toggle">
        <i class="sidebar icon"></i>
      </button>
    </div>
  </div>
</template>

<script setup>

import {getCurrentInstance, onMounted, reactive, ref, watch} from "vue";
import {useState} from "@/util/useState";
import {useRoute, useRouter} from "vue-router";
import {getSearchBlogList} from "@/api/blog";

const props = defineProps({
  blogName: {
    type: String,
    required: true
  },
  categoryList: {
    type: Array,
    required: true
  }
})

const mobileHide = ref(true)
const queryString = ref('')
const queryResult = reactive([])
const {clientSize} = useState(['clientSize'])
const route = useRoute()
const {proxy} = getCurrentInstance()

function toggle() {
  mobileHide.value = !mobileHide.value
}

const router = useRouter()

function categoryRoute(name) {
  router.push(`/category/${name}`)
}

function querySearchAsync(s, callback) {
  if (s == null
      || s.trim() === ''
      || s.indexOf('%') !== -1
      || s.indexOf('_') !== -1
      || s.indexOf('[') !== -1
      || s.indexOf('#') !== -1
      || s.indexOf('*') !== -1
      || s.trim().length > 20) {
    return
  }
  getSearchBlogList(s).then(res => {
    if (res.code === 200) {
      queryResult.splice(0, queryResult.length)
      res.data.forEach(d => queryResult.push(d))
      if (queryResult.length === 0) {
        queryResult.push({title: '无相关搜索结果'})
      }
      callback(queryResult)
    }
  }).catch(() => {
    proxy.msgError("请求失败")
  })
}

let timer = null

function debounceQuery(s, callback) {
  timer && clearTimeout(timer)
  timer = setTimeout(() => querySearchAsync(s, callback), 1000)
}

function handleSelect(item) {
  if (item.id) {
    router.push(`/blog/${item.id}`)
  }
}

//路由改变时，收起导航栏
watch(() => route.path, () => {
  mobileHide.value = true
})

const nav = ref(null)
onMounted(() => {
//监听页面滚动位置，改变导航栏的显示
  window.addEventListener('scroll', () => {
    //首页且不是移动端
    if (route.name === 'home' && clientSize.clientWidth > 768) {
      if (window.scrollY > clientSize.clientHeight / 2) {
        nav.value.classList.remove('transparent')
      } else {
        nav.value.classList.add('transparent')
      }
    }
  })
  //监听点击事件，收起导航菜单
  document.addEventListener('click', (e) => {
    //遍历冒泡
    let flag = e.path.some(item => {
      if (item === nav.value) return true
    })
    //如果导航栏是打开状态，且点击的元素不是Nav的子元素，则收起菜单
    if (!mobileHide.value && !flag) {
      mobileHide.value = true
    }
  })
})

</script>

<style scoped>
.ui.fixed.menu .container {
  width: 1400px !important;
  margin-left: auto !important;
  margin-right: auto !important;
}

.ui.fixed.menu {
  transition: .3s ease-out;
}

.ui.inverted.pointing.menu.transparent {
  background: transparent !important;
}

.ui.inverted.pointing.menu.transparent .active.item:after {
  background: transparent !important;
  transition: .3s ease-out;
}

.ui.inverted.pointing.menu.transparent .active.item:hover:after {
  background: transparent !important;
}

.el-dropdown-link {
  outline-style: none !important;
  outline-color: unset !important;
  height: 100%;
  cursor: pointer;
}

.el-dropdown-menu {
  /*margin: 7px 0 0 0 !important;*/
  padding: 0 !important;
  border: 0 !important;
  background: #1b1c1d !important;
}

.el-dropdown-menu__item {
  padding: 0 15px !important;
  color: rgba(255, 255, 255, .9) !important;
}

.el-dropdown-menu__item:hover {
  background: rgba(255, 255, 255, .08) !important;
}

.el-popper .popper__arrow::after {
  content: none !important;
}

.popper__arrow {
  display: none !important;
}

.m-search {
  min-width: 220px;
  padding: 0 !important;
}

.m-search input {
  color: rgba(255, 255, 255, .9);;
  border: 0px !important;
  background-color: inherit;
  padding: .67857143em 2.1em .67857143em 1em;
}

.m-search i {
  color: rgba(255, 255, 255, .9) !important;
}

.m-search-item {
  min-width: 350px !important;
}

.m-search-item li {
  line-height: normal !important;
  padding: 8px 10px !important;
}

.m-search-item li .title {
  text-overflow: ellipsis;
  overflow: hidden;
  color: rgba(0, 0, 0, 0.87);
}

.m-search-item li .content {
  text-overflow: ellipsis;
  font-size: 12px;
  color: rgba(0, 0, 0, .70);
}
</style>
